<template>
    <div class="card-wrap mb10 animate-on-enter">
        <a-space wrap>
            <a-button type="primary" :icon="h(PlusCircleOutlined)" @click="onAddUser">新增</a-button>
        </a-space>
    </div>
    <div class="card-wrap animate-on-enter animate-delay-1">
        <DataList ref="DataListRef" :api="getUsers" :deleteApi="deleteUser" :columns="tableColumns"
            @action="handleAction"></DataList>
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <a-modal v-model:open="openUserModal" :title="formState.id ? '编辑用户' : '新增用户'" :maskClosable="false" :footer="null">
        <a-form ref="userFormRef" :model="formState" :label-col="labelCol" :rules="rules" @finish="onUserSubmit">
            <a-form-item label="用户名" name="username">
                <a-input v-model:value="formState.username" placeholder="请填写用户名" />
            </a-form-item>
            <a-form-item label="姓名" name="real_name">
                <a-input v-model:value="formState.real_name" placeholder="请填写姓名" />
            </a-form-item>
            <a-form-item label="邮箱" name="email">
                <a-input v-model:value="formState.email" placeholder="请填写邮箱" />
            </a-form-item>
            <a-form-item label="密码" name="password">
                <a-input-password v-model:value="formState.password"
                    :placeholder="formState.id ? '留空则不修改密码' : '请填写密码'" />
            </a-form-item>
            <a-form-item label="所属角色" name="role_id">
                <a-select v-model:value="formState.role_id" placeholder="请选择角色" :options="roleOptions"
                    :field-names="{ label: 'name', value: 'id' }"></a-select>
            </a-form-item>
            <a-form-item label="状态" name="status">
                <a-radio-group v-model:value="formState.status">
                    <a-radio :value="1">开启</a-radio>
                    <a-radio :value="0">禁用</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button type="primary" html-type="submit">保存</a-button>
                <a-button style="margin-left: 10px" @click="openUserModal = false">取消</a-button>
            </a-form-item>
        </a-form>
    </a-modal>

    <!-- 编辑角色弹窗 -->
    <a-modal v-model:open="openRoleModal" title="编辑用户角色" :maskClosable="false" :footer="null">
        <a-form ref="roleFormRef" :model="roleFormState" :label-col="labelCol" :rules="roleRules"
            @finish="onRoleSubmit">
            <a-form-item label="用户" name="username">
                <a-input v-model:value="roleFormState.username" disabled />
            </a-form-item>
            <a-form-item label="所属角色" name="role_id">
                <a-select v-model:value="roleFormState.role_id" placeholder="请选择角色" :options="roleOptions"
                    :field-names="{ label: 'name', value: 'id' }"></a-select>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button type="primary" html-type="submit">保存</a-button>
                <a-button style="margin-left: 10px" @click="openRoleModal = false">取消</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { onMounted, ref, reactive, h } from 'vue';
import { message } from 'ant-design-vue';
import { PlusCircleOutlined } from '@ant-design/icons-vue';
import { getUsers, saveUser, deleteUser, getRoles } from '@/api/auth.js';

/**
 * 页面全局变量
 */
const tableColumns = [
    {
        title: '用户名',
        dataIndex: 'username'
    },
    {
        title: '姓名',
        dataIndex: 'real_name'
    },
    {
        title: '邮箱',
        dataIndex: 'email'
    },
    {
        title: '所属角色',
        dataIndex: 'role',
        customRender: ({ record }) => {
            return record.role ? record.role.name : '-';
        }
    },
    {
        title: '状态',
        dataIndex: 'status'
    },
    {
        title: '最后登录时间',
        dataIndex: 'last_login_time'
    },
    {
        title: '创建时间',
        dataIndex: 'created_at'
    },
    {
        title: '操作',
        type: 'action',
        options: [
            {
                title: '编辑',
                type: 'edit'
            },
            {
                title: '编辑角色',
                type: 'editRole'
            },
            {
                title: '删除',
                type: 'delete'
            }
        ]
    }
];

const rules = {
    username: [
        {
            required: true,
            message: '请填写用户名',
            trigger: 'change',
        },
        {
            min: 4,
            max: 32,
            message: '用户名长度为4-32个字符',
            trigger: 'change',
        }
    ],
    real_name: [
        {
            required: true,
            message: '请填写姓名',
            trigger: 'change',
        },
        {
            max: 50,
            message: '姓名不能超过50个字符',
            trigger: 'change',
        }
    ],
    email: [
        {
            type: 'email',
            message: '邮箱格式不正确',
            trigger: 'change',
        }
    ],
    password: [
        {
            required: true,
            message: '请填写密码',
            trigger: 'change',
        },
        {
            validator: (rule, value) => {
                if (!formState.id && !value) {
                    return Promise.reject('请填写密码');
                }
                if (value && value.length < 6) {
                    return Promise.reject('密码至少6个字符');
                }
                if (value && !/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/.test(value)) {
                    return Promise.reject('密码必须包含字母、数字和特殊字符');
                }
                return Promise.resolve();
            },
            trigger: 'change',
        }
    ],
    role_id: [
        {
            required: true,
            message: '请选择角色',
            trigger: 'change',
        }
    ],
    status: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change',
        }
    ]
};

const roleRules = {
    role_id: [
        {
            required: true,
            message: '请选择角色',
            trigger: 'change',
        }
    ]
};

const labelCol = {
    style: {
        width: '70px',
    },
};

const openUserModal = ref(false);
const openRoleModal = ref(false);
const roleOptions = ref([]);
const userFormRef = ref();
const roleFormRef = ref();
const DataListRef = ref();

const formState = reactive({
    id: null,
    username: '',
    nickname: '',
    email: '',
    password: '',
    role_id: null,
    status: 1
});

const roleFormState = reactive({
    id: null,
    username: '',
    role_id: null
});

/**
 * 页面生命周期
 */
onMounted(() => {
    loadRoles();
});

/**
 * 页面函数
 */

// 加载角色列表
function loadRoles() {
    getRoles().then(res => {
        if (res.code === 200) {
            roleOptions.value = res.result.list || res.result;
        }
    });
}

// 新增用户
function onAddUser() {
    resetForm();
    openUserModal.value = true;
}

// 重置表单
function resetForm() {
    userFormRef.value?.resetFields();
}

// 重置角色表单
function resetRoleForm() {
    roleFormRef.value?.resetFields();
}

// 处理操作
function handleAction(item, record) {
    if (item.type === 'edit') {
        // 编辑用户
        Object.assign(formState, {
            id: record.id,
            username: record.username,
            nickname: record.nickname,
            email: record.email || '',
            password: '',
            role_id: record.role_id,
            status: record.status
        });
        openUserModal.value = true;
    } else if (item.type === 'editRole') {
        // 编辑角色
        Object.assign(roleFormState, {
            id: record.id,
            username: record.username,
            role_id: record.role_id
        });
        openRoleModal.value = true;
    }
}

// 提交用户表单
function onUserSubmit() {
    saveUser(formState).then(res => {
        if (res.code === 200) {
            message.success(res.message);
            openUserModal.value = false;
            DataListRef.value.refreshData();
        }
    });
}

// 提交角色表单
function onRoleSubmit() {
    const submitData = {
        id: roleFormState.id,
        role_id: roleFormState.role_id
    };

    saveUser(submitData).then(res => {
        if (res.code === 200) {
            message.success(res.message);
            openRoleModal.value = false;
            DataListRef.value.refreshData();
        }
    });
}
</script>

<style lang="less" scoped></style>